const Koa = require('koa')
const app = new Koa()
const koaArtTemplateRender = require('koa-art-template');
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const { resolve } = require('path')
const registerRouter = require('./routes/index')
const errorHandler = require('./middleware/errorHandler')
const configData = require('./config') // 项目配置
const siteData = require('./config/siteData') // 站点信息

// error handler
onerror(app, {
  text: errorHandler,
  json: errorHandler,
  html: errorHandler
})

// middlewares
app.use(bodyparser())
app.use(json())
app.use(logger())

// 静态目录
app.use(require('koa-static')(__dirname + '/public'), {
  maxage: 30 * 24 * 60 * 60 * 1000, // 浏览器缓存时间
  extensions: ['html'] // 开启html静态访问
})

// 模板引擎：ArtTemplate
koaArtTemplateRender(app, {
  root: resolve(__dirname, 'views'),
  extname: '.html',
  debug: process.env.NODE_ENV !== 'production',
  // 模板变量
  imports: {
    configData,
    siteData
  }
});

// routes
app.use(registerRouter())


app.on('error', (err, ctx) => {
  
});


module.exports = app
